<template>
  <div class="app-container">
   <!-- <div class="bgWhite radius8">
      <el-form class="p20 flex col-top row-between" :model="queryParams" ref="queryForm" :inline="true"
        v-show="showSearch">
        <el-form-item label="分配规则" prop="logisticsCompany">
          <el-radio-group v-model="radioValue">
            <el-radio class="bus-radio-button-selected-bg-color " label="" value="">全部展示
            </el-radio>
            <el-radio class="bus-radio-button-selected-bg-color " v-for="item in bus_opportuity_rules_type_2"
              :label="item.value" :value="item.value">{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div> -->

    <div class="bgWhite radius8 plr20 pt30 pb30">
		<div class="mb20">
		  <span class="fb fs16">线上渠道公共商机分配规则 </span>		  
		</div>
		<div class="mb20">
			<el-form class="flex col-top row-between" :model="queryParams" ref="queryForm" :inline="true"
			  v-show="showSearch">
			  <el-form-item label="分配规则" prop="logisticsCompany" style="margin-bottom: 0;">
			    <el-radio-group v-model="radioValue">
			      <el-radio class="bus-radio-button-selected-bg-color " label="" value="">全部展示
			      </el-radio>
			      <el-radio class="bus-radio-button-selected-bg-color " v-for="item in bus_opportuity_rules_type_2"
			        :label="item.value" :value="item.value">{{ item.label }}
			      </el-radio>
			    </el-radio-group>
			  </el-form-item>
			</el-form>
		</div>
      <el-table v-loading="loading" :data="handleRadioChangeTableData"
	  :header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
	  :cell-style="{height:'54px'}"
	  >
        <el-table-column label="主键" align="center" prop="id" v-if="false" />

        <el-table-column label="部门名称" align="center" prop="deptName" />
        <el-table-column label="主管人员" align="center" prop="leader" />
        <el-table-column label="规则数量" align="center" prop="executionContent">
          <template #default="scope">
            {{ countRules(scope.row.executionContent) }}
          </template>
        </el-table-column>
        <el-table-column label="商机分配规则" align="center" prop="executionType">
          <template v-slot="scope">
            <dict-tag :options="bus_opportuity_rules_type_2" :value="scope.row.executionType" />
          </template>
        </el-table-column>

        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template #default="scope">
            <p v-if="scope.row.updateTime">{{ scope.row.updateTime }}</p>
            <p v-else>{{ scope.row.createTime }}</p>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link class="linkBtnColor" type="primary" @click="handleUpdate(scope.row)"
			v-hasPermi="['public:edit']"
			>修改分配规则
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改物流规则对话框 -->
    <el-dialog :title="title" center v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="formData" :rules="rules" label-width="90px">
        <el-form-item label="部门名称:" prop="ids">
          <el-select :disabled="true" v-model="selectValue" placeholder="Select" style="width: 800px" clearable
            multiple>
            <template #label="{ label, value }">
              <span>{{ label }}: </span>
              <span style="font-weight: bold">{{ value }}</span>
            </template>
            <el-option v-for="item in selectDept" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="分配规则:" prop="executionType">
          <el-radio-group v-model="radioAddValue">
            <el-radio class="bus-radio-button-selected-bg-color" v-for="item in bus_opportuity_rules_type_2"
              :label="item.value" :value="item.value">{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="规则内容:" :key="formData" :rules="subRules" prop="executionContent">
          <div v-for="(row, rowIndex) in formData.executionContent" :key="rowIndex" class="mb10" style="width: 100%">
            <el-select v-model="row.crop" placeholder="选择作物" style="width: 150px" :prop="'rows.' + rowIndex + '.crop'"
              prop="crop">
              <el-option v-for="item in dict_select1" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            +
            <el-select v-model="row.target" placeholder="选择靶标" style="width: 150px"
              :prop="'rows.' + rowIndex + '.target'">
              <el-option v-for="item in bus_target" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            +
            <el-select v-model="row.otherLabel" placeholder="选择其他标签" style="width: 150px"
              :prop="'rows.' + rowIndex + '.otherLabel'">
              <el-option v-for="item in bus_other_tag" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

            <el-button type="danger" class="ml15" @click="removeRow(rowIndex)">删除</el-button>
            <el-button type="defaultBtn" @click="addRow()"
              v-if="formData.executionContent.length === (rowIndex + 1)">添加</el-button>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer text-right mt30">
		  <el-button class="cancelSubBtn" @click="cancel">取 消</el-button>
		  <el-button type="primary" @click="submitForm" class="mainSubBtn">确 定</el-button>       
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="OpportunityPublicRulesSetup">
import { listAllByPublic, addPublicRules, } from "@/api/business/rules_opportunity";
import { getCropVarietyList } from "@/api/business/opportunity";

const { proxy } = getCurrentInstance();
const { bus_opportuity_rules_type_2, bus_target, bus_other_tag, bus_channel } =
  proxy.useDict("bus_opportuity_rules_type_2", "bus_target", "bus_other_tag", "bus_channel");

//默认单选参数
const radioValue = ref("");
const radioAddValue = ref("");

//默认下拉
var selectDept = [];
const selectValue = ref([]);

const dict_select1 = ref([]);

//折叠
const isExpandAll = ref(true);
//刷新表单
const refreshTable = ref(true);
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 物流规则表格数据
const rulesList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  level: 3,
  channel: "1001",
});
// 表单参数
const formData = ref({
  ids: [],
  executionType: "",
  executionContent: [
    {
      crop: "",
      target: "",
      otherLabel: "",
    },
  ],
});

// 内联表 表单校验规则
const customValidator = (rule, value, callback) => {
  value.forEach(e => {
    if (!e.crop && !e.target && !e.otherLabel)
      return callback(new Error("每条规则内容,至少需要选择1项"));
  });
  callback();
};

// 表单校验
const rules = ref({
  ids: [{ required: true, message: "选择部门不能为空", trigger: "blur" }],
  executionType: [
    { required: true, message: "分配规则不能为空", trigger: "blur" },
  ],
  executionContent: [{ validator: customValidator, trigger: "blur" }],
});

// 计算规则数量
function countRules(rules) {
  if (!rules) return 0;
  return rules.length;
}

// 构筑 生产资料编译为字典数据
function buildDict() {
  getCropVarietyList().then((response) => {
    var dictArray = response.data;
    dictArray.forEach((element) => {
      dict_select1.value.push({
        label: element.cropName,
        value: element.id,
      });
    });
  });
}

/** 查询物流规则列表 */
function getList() {
  loading.value = true;
  listAllByPublic(queryParams.value).then((response) => {
    rulesList.value = proxy.handleTree(response.data, "deptId");
    total.value = response.total;
    loading.value = false;
  });
}

function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  proxy.resetForm("form");
  formData.value = {
    ids: [],
    executionType: "",
    executionContent: [
      {
        crop: "",
        target: "",
        otherLabel: "",
      },
    ],
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

// 列表行数据过滤
const handleRadioChangeTableData = computed(() => {
  if (radioValue.value === "") {
    // 如果过滤条件为空，返回所有数据
    return rulesList.value;
  } else {
    // 否则，返回过滤后的数据
    // 在这里添加你的过滤逻辑
    // 例如，根据 name 属性进行过滤
    return rulesList.value.filter(
      (item) => item.executionType === radioValue.value
    );
  }
});

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 行 修改分配规则 初始化数据 */
function buildUpdateData(row) {
  if (row.executionContent) {
    formData.value.executionContent = row.executionContent;
  }

  radioAddValue.value = row.executionType;

  selectDept = [];
  selectValue.value = [];

  selectDept.push({
    label: row.deptName,
    value: row.deptId,
  });
  selectValue.value.push(row.deptId);
}

/** 行 修改分配规则 */
function handleUpdate(row) {
  getList();
  reset();
  buildUpdateData(row);

  open.value = true;
  title.value = "修改分配规则";
}

/** 提交按钮 */
function submitForm() {
  formData.value.ids = selectValue.value;
  formData.value.executionType = radioAddValue.value;

  proxy.$refs["form"].validate((valid) => {
    if (valid) {
      addPublicRules(formData.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

//删除 内联表行
const removeRow = (rowIndex) => {
  formData.value.executionContent.splice(rowIndex, 1);
  var l = formData.value.executionContent.length;
  if (l < 1) {
    addRow()
  }
};

//添加 内联表行
const addRow = () => {
  formData.value.executionContent.push({
    crop: null,
    target: null,
    otherLabel: null,
  });
};

getList();
buildDict();
watch(() => bus_channel.value, arr => {
  queryParams.value.channel = arr[0].value
  console.log("ol_public", queryParams.value.channel)
})
</script>
